package com.jiangjiang.eshop.order.schedule;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.jiangjiang.eshop.common.help.DateHelper;
import com.jiangjiang.eshop.logistics.service.LogisticsFacadeService;
import com.jiangjiang.eshop.order.dto.OrderInfoDTO;
import com.jiangjiang.eshop.order.service.OrderInfoService;
import com.jiangjiang.eshop.order.status.LoggedOrderStateManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName AutoConfirmReceiptTask
 * @Description TODO
 * @Author jhw
 * @Date 2021/8/24 22:35
 * @Version 1.0
 **/
@Slf4j
@Component
@Transactional(rollbackFor = Exception.class)
public class AutoConfirmReceiptTask {

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private LogisticsFacadeService logisticsFacadeService;
    @Autowired
    private DateHelper dateHelper;
    @Autowired
    private LoggedOrderStateManager orderStateManager;


    @Scheduled(fixedRate = 1 * 60 * 1000)
    public void execute(){
        try {
            List<OrderInfoDTO> orders = orderInfoService.queryAllUnReceive();
            if(CollectionUtils.isEmpty(orders)){
                return;
            }
            for (OrderInfoDTO order : orders) {

                Date signedTime = logisticsFacadeService.getSignedTime(order.getId(), order.getOrderNo());
                if(Objects.isNull(signedTime)){
                    continue;
                }

                if(dateHelper.getCurrentDate().getTime() - order.getGmtCreate().getTime() > 7 * 24 * 60 * 60 * 1000){
                    orderStateManager.confirmReceipt(order);
                    order.setConfirmReceiptTime(dateHelper.getCurrentDate());
                    orderInfoService.updateOrderInfo(order);
                }

            }

        }catch (Exception e){
            log.warn("AutoConfirmReceiptTask error",e);
        }
    }
}
